#include "Acceptor.hpp"

namespace se {

Acceptor::Acceptor(const char *ip, unsigned short port) : _socketAddress(ip, port), _socket() {
    this->setReuse(SO_REUSEADDR);
    this->setReuse(SO_REUSEPORT);

    struct sockaddr_in *address = this->_socketAddress.getAddress();
    ::bind(this->_socket.getFileDescriptor(), (struct sockaddr *)address, sizeof *address);
    ::listen(this->_socket.getFileDescriptor(), 1024);
}

int Acceptor::accept() {
    return ::accept(this->_socket.getFileDescriptor(), nullptr, nullptr);
}

int Acceptor::getFileDescriptor() const {
    return this->_socket.getFileDescriptor();
}

void Acceptor::setReuse(int __optname) {
    int reuse = 0;
    if (::setsockopt(this->_socket.getFileDescriptor(), SOL_SOCKET, __optname, &reuse, sizeof reuse)) {
        ::perror("setsockopt");
    }
}

}  // namespace se